from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from app import db
from app.models import Task

# 创建蓝图
main = Blueprint('main', __name__)

@main.route('/')
def index():
    """主页 - 显示所有任务"""
    # 获取筛选参数
    status_filter = request.args.get('status', 'all')
    priority_filter = request.args.get('priority', 'all')
    search_query = request.args.get('search', '')
    
    # 构建查询
    query = Task.query
    
    # 应用筛选条件
    if status_filter != 'all':
        query = query.filter(Task.status == status_filter)
    
    if priority_filter != 'all':
        query = query.filter(Task.priority == priority_filter)
    
    if search_query:
        query = query.filter(Task.title.contains(search_query))
    
    # 按创建时间倒序排列
    tasks = query.order_by(Task.created_at.desc()).all()
    
    return render_template('index.html', 
                         tasks=tasks, 
                         status_filter=status_filter,
                         priority_filter=priority_filter,
                         search_query=search_query)

@main.route('/add_task', methods=['GET', 'POST'])
def add_task():
    """添加新任务"""
    if request.method == 'POST':
        title = request.form.get('title')
        description = request.form.get('description')
        priority = request.form.get('priority', 'medium')
        due_date_str = request.form.get('due_date')
        
        # 验证必填字段
        if not title:
            flash('任务标题不能为空！', 'error')
            return redirect(url_for('main.add_task'))
        
        # 处理日期
        due_date = None
        if due_date_str:
            try:
                due_date = datetime.strptime(due_date_str, '%Y-%m-%d').date()
            except ValueError:
                flash('日期格式不正确！', 'error')
                return redirect(url_for('main.add_task'))
        
        # 创建新任务
        task = Task(
            title=title,
            description=description,
            priority=priority,
            due_date=due_date
        )
        
        try:
            db.session.add(task)
            db.session.commit()
            flash('任务添加成功！', 'success')
            return redirect(url_for('main.index'))
        except Exception as e:
            db.session.rollback()
            flash(f'添加任务时发生错误：{str(e)}', 'error')
            print(f"数据库错误: {e}")  # 添加调试信息
            return redirect(url_for('main.add_task'))
    
    return render_template('add_task.html')

@main.route('/edit_task/<int:task_id>', methods=['GET', 'POST'])
def edit_task(task_id):
    """编辑任务"""
    task = Task.query.get_or_404(task_id)
    
    if request.method == 'POST':
        title = request.form.get('title')
        description = request.form.get('description')
        priority = request.form.get('priority')
        status = request.form.get('status')
        due_date_str = request.form.get('due_date')
        
        # 验证必填字段
        if not title:
            flash('任务标题不能为空！', 'error')
            return redirect(url_for('main.edit_task', task_id=task_id))
        
        # 处理日期
        due_date = None
        if due_date_str:
            try:
                due_date = datetime.strptime(due_date_str, '%Y-%m-%d').date()
            except ValueError:
                flash('日期格式不正确！', 'error')
                return redirect(url_for('main.edit_task', task_id=task_id))
        
        # 更新任务
        task.title = title
        task.description = description
        task.priority = priority
        task.status = status
        task.due_date = due_date
        task.updated_at = datetime.utcnow()
        
        try:
            db.session.commit()
            flash('任务更新成功！', 'success')
            return redirect(url_for('main.index'))
        except Exception as e:
            db.session.rollback()
            flash('更新任务时发生错误！', 'error')
    
    return render_template('edit_task.html', task=task)

@main.route('/delete_task/<int:task_id>', methods=['POST'])
def delete_task(task_id):
    """删除任务"""
    task = Task.query.get_or_404(task_id)
    
    try:
        db.session.delete(task)
        db.session.commit()
        flash('任务删除成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('删除任务时发生错误！', 'error')
    
    return redirect(url_for('main.index'))

@main.route('/toggle_status/<int:task_id>', methods=['POST'])
def toggle_status(task_id):
    """切换任务状态"""
    task = Task.query.get_or_404(task_id)
    
    # 切换状态逻辑
    if task.status == 'todo':
        task.status = 'in_progress'
    elif task.status == 'in_progress':
        task.status = 'completed'
    else:  # completed
        task.status = 'todo'
    
    task.updated_at = datetime.utcnow()
    
    try:
        db.session.commit()
        return jsonify({'success': True, 'new_status': task.status})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)})

@main.route('/api/tasks')
def api_tasks():
    """API接口 - 获取任务列表"""
    tasks = Task.query.order_by(Task.created_at.desc()).all()
    return jsonify([task.to_dict() for task in tasks])

@main.route('/api/tasks/<int:task_id>')
def api_task_detail(task_id):
    """API接口 - 获取单个任务详情"""
    task = Task.query.get_or_404(task_id)
    return jsonify(task.to_dict())